package cn.itcast.wanxinp2p.consumer.service.iml;

import cn.itcast.wanxinp2p.api.account.model.AccountDTO;
import cn.itcast.wanxinp2p.api.account.model.AccountRegisterDTO;
import cn.itcast.wanxinp2p.api.consumer.model.ConsumerRegisterDTO;
import cn.itcast.wanxinp2p.common.domain.BusinessException;
import cn.itcast.wanxinp2p.common.domain.CommonErrorCode;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.domain.consumer.ConsumerErrorCode;
import cn.itcast.wanxinp2p.consumer.agent.AccountApiAgent;
import cn.itcast.wanxinp2p.consumer.entity.Consumer;
import cn.itcast.wanxinp2p.consumer.mapper.ConsumerMapper;
import cn.itcast.wanxinp2p.consumer.service.ConsumerRegisterTCC;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.Hmily;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * TCC : try ,confirm ,cancel
 *
 *
 * </p>
 *
 * @author <a href=mailto:zhaoboying@itcast.cn> Tao </a>
 * @version 1.0.0
 * @motto Talk is cheap, show me the code!
 * @since 2022-03-31 10:43:16
 */
@Service
@Slf4j
public class ConsumerRegisterTCCImpl implements ConsumerRegisterTCC {

    @Autowired
    private AccountApiAgent accountApiAgent;

    @Autowired
    private ConsumerMapper consumerMapper;


    @Hmily(confirmMethod = "confirmMethod",cancelMethod = "cancelMethod")
    @Override
    public void tryMethod(ConsumerRegisterDTO consumerRegisterDTO) {
        log.info("注册业务的TCC 的 try..........................");
        // 负责远程调用！
        AccountRegisterDTO accountRegisterDTO = new AccountRegisterDTO();
        BeanUtils.copyProperties(consumerRegisterDTO, accountRegisterDTO);
        RestResponse<AccountDTO> restResponse = accountApiAgent.register(accountRegisterDTO);
        if (restResponse.getCode() != CommonErrorCode.SUCCESS.getCode()) {
            throw new BusinessException(ConsumerErrorCode.E_140106);
        }

    }

    @Override
    public void confirmMethod(ConsumerRegisterDTO consumerRegisterDTO) {
        // 无需关注
        log.info("注册业务的TCC consumer 的 confirm..........................");
    }

    @Override
    public void cancelMethod(ConsumerRegisterDTO consumerRegisterDTO) {
        // 业务回滚，执行补偿行为 （逆运算）删除用户
        log.info("注册业务的TCC  consumer 的 cancel begin..........................");
        consumerMapper.delete(new LambdaQueryWrapper<Consumer>().eq(Consumer::getMobile, consumerRegisterDTO.getMobile()));
        log.info("注册业务的TCC  consumer 的 cancel end..........................");
    }
}
